/**
 * 
 */
package kr.co.insoft.auth.service.mail.impl;

import java.util.HashSet;
import java.util.concurrent.TimeUnit;

import kr.co.insoft.auth.model.mail.MaillingFormModel;
import kr.co.insoft.auth.model.members.JoinFormModel;
import kr.co.insoft.auth.repository.mail.MaillingRepository;
import kr.co.insoft.auth.repository.mail.VelocityEmailSender;
import kr.co.insoft.auth.repository.members.JoinRepository;
import kr.co.insoft.auth.service.mail.MailSendService;
import kr.co.insoft.framework.exceptions.ExceptionCode;
import kr.co.insoft.framework.exceptions.ServiceException;
import kr.co.insoft.framework.resolver.MessageResolver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @author IN-SOFT Inc. GoodwillDD(sylee@in-soft.co.kr)
 * 
 */
@Service
public class MailSendServiceImpl implements MailSendService {

	private static final Logger logger = LoggerFactory
			.getLogger(MailSendServiceImpl.class);

	@Autowired
	VelocityEmailSender velocityEmailSender;

	@Autowired
	MaillingRepository maillingRepository;

	@Value("#{mail['mail.system.id']}")
	String systemSender;

	@Value("#{mail['auth.server.apiurl']}")
	String authServerApiUrl;

	@Autowired
	MessageResolver messageResolver;

	@Autowired
	JoinRepository joinRepository;

	@Override
	@Scheduled(fixedDelay = 30 * 1000, initialDelay = 30 * 1000)
	public void send() throws ServiceException {
		HashSet<MaillingFormModel> mails = null;
		try {
			RegistrationMail mailer = null;
			JoinFormModel joinForm = null;
			mails = maillingRepository.checkMails();
			for (MaillingFormModel mail : mails) {
				joinForm = joinRepository.getUser(mail.getUserid());
				mailer = new RegistrationMail(velocityEmailSender, joinForm,
						mail, systemSender,
						messageResolver.message("mail.registration.subject"),
						authServerApiUrl);
				mailer.run();
				TimeUnit.SECONDS.sleep(4L);
			}
		} catch (Exception e) {
			logger.error(ExceptionCode.SERVICE_EXCEPTION, e);
		} finally {
			try {
				maillingRepository.completedMails(mails);
			} catch (Exception e2) {
				logger.error(ExceptionCode.SERVICE_EXCEPTION, e2);
			}
		}
	}

	@Override
	@Scheduled(fixedDelay = 10 * 60 * 1000, initialDelay = 30 * 1000)
	public void cleanMails() {
		try {
			maillingRepository.cleanMails();
		} catch (Exception e) {
			logger.error(ExceptionCode.SERVICE_EXCEPTION, e);
		}
	}
}
